package com.example.netease.notepage;

import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TextView;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class DetailActivity extends AppCompatActivity {

    public EditText textView;
    private int contetId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        //新页面接收数据
        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        String content = bundle.getString("content");

        contetId = bundle.getInt("contentId");
        textView = (EditText)findViewById(R.id.editText);
        textView.setText(content);
        textView.setSelection(content.length());
    }

    @Override
    protected void onPause() {
        super.onPause();

//        Intent intent =getIntent();
//        //这里使用bundle绷带来传输数据
//        Bundle bundle =new Bundle();
//        //传输的内容仍然是键值对的形式
//        bundle.putString("content",textView.getText().toString());//回发的消息,hello world from secondActivity!
//        intent.putExtras(bundle);
//        setResult(RESULT_OK, intent);

        if (contetId < 0 && textView.getText().toString().length()<=0) {

        } else {
            MyDatabaseHelper dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 1);
            Date date = new Date(System.currentTimeMillis());
            SQLiteDatabase sqliteDatabase = dbHelper.getReadableDatabase();
            ContentValues values = new ContentValues();
            values.put("content", textView.getText().toString());
            values.put("updateTime", date.getTime());

            if (contetId >= 0) {
                String[] args = {String.valueOf(contetId)};
                if (textView.getText().toString().length()<=0) {
                    sqliteDatabase.delete("book", "id=?", args);
                } else {
                    sqliteDatabase.update("book", values, "id=?", args);
                }
            } else {
                values.put("createTime", date.getTime());
                sqliteDatabase.insert("book", null, values);
            }
        }
    }
}
